import { App, Button, Input, Select } from 'antd';
import React, { useCallback, useMemo, useState } from 'react';
import { useContextSelector } from 'use-context-selector';

import FormLabel from '@/components/MyBox/FormLabel';
import MyModal from '@/components/MyModal';
import QuestionTip from '@/components/tooltip/QuestionTip';
import { useRequest2 } from '@/hooks/use-request';
import { t } from '@/locales/i18n';
import {
  FlowNodeOutputTypeEnum,
  toolValueTypeList,
  WorkflowIOValueTypeEnum,
} from '@/types/workflow/constant';
import { FlowNodeInputItemType } from '@/types/workflow/io';

import { WorkflowContext } from '../../../context';
import { defaultEditFormData } from '../render/RenderToolInput/EditFieldModal';

const { TextArea } = Input;

const ToolParamsEditModal = ({
  defaultValue = defaultEditFormData,
  nodeId,
  onClose,
}: {
  defaultValue: FlowNodeInputItemType;
  nodeId: string;
  onClose: () => void;
}) => {
  const onChangeNode = useContextSelector(WorkflowContext, (v) => v.onChangeNode);
  const { message } = App.useApp();
  const [value, setValue] = useState<FlowNodeInputItemType>(defaultValue);

  const { runAsync: onClickSubmit } = useRequest2(
    async (e: FlowNodeInputItemType) => {
      e.key = e.key.trim();

      const inputConfig: FlowNodeInputItemType = {
        ...e,
        description: e.toolDescription,
        label: e.key,
      };
      if (defaultValue.key) {
        // edit
        onChangeNode({
          nodeId,
          type: 'replaceInput',
          key: defaultValue.key,
          value: inputConfig,
        });
        onChangeNode({
          nodeId,
          type: 'replaceOutput',
          key: defaultValue.key,
          value: {
            ...e,
            id: e.key,
            label: e.key,
            type: FlowNodeOutputTypeEnum.static,
          },
        });
      } else {
        // create
        onChangeNode({
          nodeId,
          type: 'addInput',
          value: {
            ...e,
            label: e.key,
          },
        });
        onChangeNode({
          nodeId,
          type: 'addOutput',
          value: {
            ...e,
            id: e.key,
            label: e.key,
            type: FlowNodeOutputTypeEnum.static,
          },
        });
      }
      onClose();
    },
    {
      onSuccess: () => {
        onClose();
      },
    },
  );

  const onClickSubmitError = useCallback(
    (e: Record<string, { message?: string }>) => {
      const errorItem = Object.values(e).find((item) => item.message);
      if (errorItem?.message) {
        message.warning(errorItem.message);
      }
    },
    [message],
  );

  const showEnumInput = useMemo(() => {
    return !(
      value.valueType === WorkflowIOValueTypeEnum.boolean ||
      value.valueType === WorkflowIOValueTypeEnum.arrayBoolean
    );
  }, [value]);

  return (
    <MyModal isOpen iconSrc="modal/edit" title={t('tool_field')} onClose={onClose}>
      <div>
        <div className="mb-5 flex items-center gap-2">
          <FormLabel>{t('core.module.Data Type')}</FormLabel>
          <div>
            <Select
              popupClassName="workflow-dropdown"
              options={toolValueTypeList}
              value={value.valueType}
              onChange={(e: any) => {
                setValue((prev) => {
                  return {
                    ...prev,
                    valueType: e,
                  };
                });
              }}
            />
          </div>
        </div>
        <div className="mb-5 flex items-center gap-2">
          <FormLabel>{t('tool_params.params_name')}</FormLabel>
          <Input
            // bg={'myGray.50'}
            className="bg-gray-500"
            value={value.key}
            onChange={(e) => {
              setValue((prev) => {
                return {
                  ...prev,
                  key: e.target.value,
                };
              });
            }}
            placeholder={t('tool_params.params_name_placeholder')}
          />
        </div>
        <div className={`flex items-center ${showEnumInput ? 'mb-5' : 'mb-0'}`}>
          <FormLabel>{t('tool_params.params_description')}</FormLabel>
          <Input
            // bg={'myGray.50'}
            className="bg-gray-500"
            value={value.toolDescription}
            onChange={(e) => {
              setValue((prev) => {
                return {
                  ...prev,
                  toolDescription: e.target.value,
                };
              });
            }}
            placeholder={t('tool_params.params_description_placeholder')}
          />
        </div>
        {showEnumInput && (
          <div>
            <div className="mb-2 flex items-center gap-2">
              <FormLabel>{t('tool_params.enum_values')}</FormLabel>
              <QuestionTip title={t('tool_params.enum_values_tip')} />
            </div>
            <TextArea
              // bg={'myGray.50'}
              className="bg-gray-500"
              value={value.enum}
              onChange={(e) => {
                setValue((prev) => {
                  return {
                    ...prev,
                    enum: e.target.value,
                  };
                });
              }}
              placeholder={t('tool_params.enum_placeholder')}
            />
          </div>
        )}
      </div>
      <div className="ml-auto mt-4 flex gap-2">
        <Button onClick={onClose}>{t('common.Close')}</Button>
        <Button
          onClick={() => {
            onClickSubmit(value);
          }}
        >
          {t('common.Confirm')}
        </Button>
      </div>
    </MyModal>
  );
};

export default React.memo(ToolParamsEditModal);
